package com.webserver.servlet;

import com.webserver.http.HttpRequest;
import com.webserver.http.HttpResponse;

import java.io.File;
import java.util.HashMap;
import java.util.Map;

/**
 *  用于处理请求的Servlet
 *  ClientHandler处理请求的环节调用当前类的service方法完成处理细节
 */
public class DispatcherServlet {
    public java.lang.String service(HttpRequest request, HttpResponse response){
        String path = request.getUri();//获取抽象路径
        System.out.println("抽象路径========> "+path);

        File file = new File("./webapps" + path);
        if (file.exists() && file.isFile()){//是否存在
            Map<String,String> map = new HashMap<>();
            map.put("html","text/html");
            map.put("css","text/css");
            map.put("js","application/javascript");
            map.put("png","image/png");
            map.put("gif","image/gif");
            map.put("jpg","image/jpeg");
            String Type =
                    map.get(file.getName().substring(file.getName().lastIndexOf(".")+1));
            response.addHeader("Content-Type",Type);
            response.addHeader("Content-Length",file.length()+"");
            response.setEntity(file);
        }else {
            File notFoundPage = new File("./webapps/root/404.html");
            response.addHeader("Content-Type","text/html");
            response.addHeader("Content-Length",notFoundPage.length()+"");
            response.setStatusCode(404);
            response.setStatusReason("NotFound");
            response.setEntity(notFoundPage);
        }

        //设置通用响应头
        response.addHeader("Server","WebServer");
        return path;
    }
}
